package com.qo.qsdk;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;

import androidx.annotation.NonNull;

import com.google.android.play.core.review.ReviewInfo;
import com.google.android.play.core.review.ReviewManager;
import com.google.android.play.core.review.ReviewManagerFactory;
import com.google.android.play.core.tasks.OnCompleteListener;
import com.google.android.play.core.tasks.Task;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.qo.qsdk.base.IPay;
import com.qo.qsdk.base.IPayConsumeListener;
import com.qo.qsdk.base.IPayExecResultListener;
import com.qo.qsdk.base.IPayListener;
import com.qo.qsdk.base.PayError;
import com.qo.qsdk.base.PayType;
import com.qo.qsdk.config.QSDKLanguage;
import com.qo.qsdk.event.Publisher;
import com.qo.qsdk.event.QSDKEvent;
import com.qo.qsdk.http.QCommonResultBean;
import com.qo.qsdk.http.QResultCallback;
import com.qo.qsdk.http.QSDKHttp;
import com.qo.qsdk.listener.CustomerResultListener;
import com.qo.qsdk.listener.ExitResultListener;
import com.qo.qsdk.listener.FacebookLikeResultListener;
import com.qo.qsdk.listener.GuestBindResultListener;
import com.qo.qsdk.listener.HistoryResultListener;
import com.qo.qsdk.listener.InitResultListener;
import com.qo.qsdk.listener.LoginResultListener;
import com.qo.qsdk.listener.LogoutResultListener;
import com.qo.qsdk.listener.PayResultListener;
import com.qo.qsdk.listener.ReviewResultListener;
import com.qo.qsdk.listener.SubmitRoleResultListener;
import com.qo.qsdk.listener.SwitchAccountResultListener;
import com.qo.qsdk.listener.SwitchLanguageListener;
import com.qo.qsdk.model.InitModel;
import com.qo.qsdk.model.SDKInfoModel;
import com.qo.qsdk.model.UserModel;
import com.qo.qsdk.model.VerifyResult;
import com.qo.qsdk.param.GameRoleParams;
import com.qo.qsdk.param.PayParams;
import com.qo.qsdk.pay.Pay;
import com.qo.qsdk.ui.AccountActivity;
import com.qo.qsdk.ui.ExitActivity;
import com.qo.qsdk.ui.FloatActivity;
import com.qo.qsdk.ui.HisActivity;
import com.qo.qsdk.ui.LoadingDialog;
import com.qo.qsdk.ui.PayActivity;
import com.qo.qsdk.ui.QSDKListener;
import com.qo.qsdk.ui.TipActivity;
import com.qo.qsdk.ui.base.DragViewLayout;
import com.qo.qsdk.ui.base.Float;
import com.qo.qsdk.ui.base.floater.FloatButtonUtil;
import com.qo.qsdk.utils.AppsFlyerManager;
import com.qo.qsdk.utils.FacebookManager;
import com.qo.qsdk.utils.FirebaseManager;
import com.qo.qsdk.utils.Language;
import com.qo.qsdk.utils.LogManager;
import com.qo.qsdk.utils.QSDKHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class QSDK {

    private static final String TAG = QSDK.class.getSimpleName();
    private volatile static QSDK INSTANCE;
    private static final String INIT_JSON_FILE = "qsdk.json";

    private static final int InitReady      = 0;
    private static final int Initializing   = 1;
    private static final int Initialized    = 2;
    private AtomicInteger mInitAtomic = new AtomicInteger(InitReady);
    private AtomicBoolean mLoginAtomic = new AtomicBoolean(false);
    private AtomicBoolean mPayAtomic = new AtomicBoolean(false);
    private AtomicBoolean mExitAtomic = new AtomicBoolean(false);

    private Activity mActivity;

    public static QSDK getInstance() {
        if (INSTANCE == null) {
            synchronized (QSDK.class) {
                if (INSTANCE == null) {
                    INSTANCE = new QSDK();
                }
            }
        }
        return INSTANCE;
    }

    public void applicationOnCreate(Context context) {
        SDKInfoModel config = QSDK.getInstance().getConfig(context);
        if (config != null) {
            FacebookManager.getInstance().init(context);
            AppsFlyerManager.getInstance().init(context, config.getAppsflyerKey());
            FirebaseManager.getInstance().init(context);
        }
    }

    public SDKInfoModel getConfig(Context c) {
        String initJson = QSDKHelper.getConfigure(c, INIT_JSON_FILE);
        if (initJson == null || initJson.length() == 0) {
            return null;
        }

        try {
            return new Gson().fromJson(initJson, SDKInfoModel.class);

        }catch (JsonSyntaxException e){
            return null;
        }
    }

    private InitResultListener mInitResultListener;
    public void init(Activity activity, InitResultListener initResultListener) {
        mActivity = activity;
        if (isInitializing() || isInitialized()) {
            Log.e(TAG, "已经初始化或正在初始化:isInitializing=>" + (isInitializing()?1:0) + ",isInitialized" + (isInitialized()?1:0));
            return;
        }

        this.mInitResultListener = initResultListener;
        mInitAtomic.set(Initializing);

        LogManager.getInstance().init(activity);


        String initJson = QSDKHelper.getConfigure(activity, INIT_JSON_FILE);
        if (initJson == null || initJson.length() == 0) {
            initFail(1003, INIT_JSON_FILE + " not found");
            return;
        }

        try {
            SDKInfoModel mConfigureModel = getConfig(activity);
            if (mConfigureModel == null) {
                initFail(1003, INIT_JSON_FILE + " not found");
                return;
            }
            QSDKHelper.getInstance().setConfigureModel(mConfigureModel);
        }catch (JsonSyntaxException e){
            initFail(1004, INIT_JSON_FILE + " json error");
            return;
        }

        initLanguage(activity);

        QSDKHelper.getInstance().getDeviceId(activity, new QSDKHelper.GetDeviceIdCallback() {
            @Override
            public void onResult(String id) {
                Log.e(TAG, "deviceId=>" + (id == null ? "" : id));
                QSDKHelper.getInstance().getConfigureModel().setDeviceId(id);
                reqInit(activity);
            }
        });
    }

    private void reqInit(Activity activity) {
        QSDKHttp.getInstance().init(activity, new QResultCallback<QCommonResultBean<InitModel>>() {
            @Override
            public void onSuccess(QCommonResultBean<InitModel> response) {
                QSDKHelper.getInstance().getConfigureModel().setInitModel(response.getBody());
                initSuccess(activity);
            }

            @Override
            public void onError(int code, String msg) {
                initFail(code, msg);
            }
        });
    }

    private boolean isInitialized() {
        return mInitAtomic.get() == Initialized;
    }

    private boolean isInitializing() {
        return mInitAtomic.get() == Initializing;
    }

    private void initSuccess(Activity activity) {
        mInitAtomic.set(Initialized);
        checkUnFinishPay(activity);
        if (mInitResultListener != null) mInitResultListener.onSuccess();
        LogManager.getInstance().init(activity);
    }

    private void initFail(int code, String msg) {
        mInitAtomic.set(InitReady);
        if (mInitResultListener != null) mInitResultListener.onError(code, msg);
    }

    private LoginResultListener mLoginResultListener;
    public void login(Activity activity, LoginResultListener loginResultListener) {
        login(activity, false, false, false, loginResultListener);
    }

    private boolean isLogin;
    private void login(Activity activity, boolean isHis, boolean isBind, boolean isSwitch, LoginResultListener loginResultListener) {
        if (!isInitialized()) {
            Log.e(TAG, "未初始化");
            return;
        }
        if (isLogining()) {
            Log.e(TAG, "正在登录");
            return;
        }

        mLoginResultListener = loginResultListener;
        if (mLoginAtomic.getAndSet(true)) {
            Log.e(TAG, "正在登录");
            return;
        }

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(activity, AccountActivity.class);
                AccountActivity.isHis = isHis;
                AccountActivity.isBind = isBind;
                AccountActivity.isSwitch = isSwitch;
                activity.startActivity(intent);
            }
        });

//        logout(activity, new LogoutResultListener() {
//            @Override
//            public void onSuccess() {
//
//
//            }
//
//            @Override
//            public void onError(int code, String msg) {
//                loginFail(code, msg);
//            }
//        });
    }

    private boolean isLogining() {
        return mLoginAtomic.get();
    }

    private boolean isExiting() {
        return mExitAtomic.get();
    }

    public void loginFinish() {
        mLoginAtomic.set(false);
    }
    public void loginSuccess(String token) {
        loginFinish();
        isLogin = true;
        if (mLoginResultListener != null) mLoginResultListener.onSuccess(token);
    }

    public void loginCancel() {
        loginFinish();
        isLogin = false;
        if (mLoginResultListener != null) mLoginResultListener.onCancel();
    }

    public void loginFail(int code, String msg) {
        loginFinish();
        isLogin = false;
        if (mLoginResultListener != null) mLoginResultListener.onError(code, msg);
    }

    public void paymentFinish() {
        mPayAtomic.set(false);
    }

    private LogoutResultListener mLogoutResultListener;
    public void logout(Activity activity, LogoutResultListener logoutResultListener) {
        QSDKHelper.getInstance().delItem(activity, AccountActivity.KEY);
        QSDKHelper.getInstance().setUserModel(activity, new UserModel());
        isLogin = false;
        if (logoutResultListener != null) logoutResultListener.onSuccess();
    }

    private SwitchAccountResultListener mSwitchAccountResultListener;
    public void switchAccount(Activity activity, SwitchAccountResultListener switchAccountResultListener) {
        QSDKHelper.getInstance().delItem(activity, AccountActivity.KEY);
        login(activity, false, false, true, new LoginResultListener() {
            @Override
            public void onSuccess(String token) {
                if (switchAccountResultListener != null) switchAccountResultListener.onSuccess(token);
            }

            @Override
            public void onCancel() {
                if (switchAccountResultListener != null) switchAccountResultListener.onCancel();
            }

            @Override
            public void onError(int code, String msg) {
                if (switchAccountResultListener != null) switchAccountResultListener.onError(code, msg);
            }
        });
    }

    public Pay getPay(Activity activity) {
//        Class<?> glass = null;
//        String class_name = "com.qo.qsdk.pay.Pay";
//        try {
//            glass = Class.forName(class_name);
//        } catch (ClassNotFoundException e) {
//            Log.e(TAG, "invokeGetInstance: " + "do not find " + class_name);
//        }
//        try {
//            return  (IPay) glass.newInstance();
//        } catch (Exception exception) {
//            Log.e(TAG, "glass.newInstance(): " + "do not find " + class_name);
//        }

        return Pay.getInstance();
    }

    IPay mIPay;
    public void checkUnFinishPay(Activity activity) {
        if (mIPay == null) {
            mIPay = getPay(activity);
            if (mIPay != null) {
                mIPay.start(activity, new IPayListener() {

                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onSuccess(IPayExecResultListener iPayExecResultListener, PayType type, String orderNo, String purchaseToken) {
                        reqVerifyPay(activity, iPayExecResultListener, type, orderNo, purchaseToken);
                    }

                    @Override
                    public void onFail(PayError code, String msg) {

                    }
                });
            }
        }
        if (mIPay != null) mIPay.query(activity);
    }

    private void reqVerifyPay(Activity activity, IPayExecResultListener iPayExecResultListener, PayType type, String orderNo, String purchaseToken) {
        QSDKHttp.getInstance().verifyPay(activity, purchaseToken, orderNo, new QResultCallback<QCommonResultBean<VerifyResult>>() {
            @Override
            public void onSuccess(QCommonResultBean<VerifyResult> response) {
                if (iPayExecResultListener != null) {
                    iPayExecResultListener.onSuccess(new IPayConsumeListener() {
                        @Override
                        public void onSuccess() {

                        }

                        @Override
                        public void onFail() {

                        }
                    });
                }
            }

            @Override
            public void onError(int code, String msg) {
                if (iPayExecResultListener != null) iPayExecResultListener.onFail();
            }
        });
    }

    private PayResultListener mPayResultListener;
    public void pay(Activity activity, PayParams payParams, PayResultListener payResultListener) {
        if (!isInitialized()) {
            Log.e(TAG, "未初始化");
            return;
        }

        if (payParams == null) {
            Log.e(TAG, "payparams 为空");
            if (payResultListener != null) payResultListener.onError(1001, "参数不能为空");
            return;
        }

        if (payParams.getServerId().length() == 0 || payParams.getRoleId().length() == 0 || payParams.getRoleName().length() == 0) {
            Log.e(TAG, "serverId或roleId或roleName为空");
            if (payResultListener != null) payResultListener.onError(1001, "serverId或roleId或roleName为空");
            return;
        }

        if (mPayAtomic.get()) {
            Log.e(TAG, "正在支付");
            return;
        }

        if (!isLogin) {
            Log.e(TAG, "未登录");
            return;
        }

        mPayResultListener = payResultListener;
        if (mPayAtomic.getAndSet(true)) {
            Log.e(TAG, "正在支付");
            return;
        }

        PayActivity.start(activity, payParams);
    }

    public void paymentSuccess() {
        paymentFinish();
        if (mPayResultListener != null) mPayResultListener.onSuccess();
    }

    public void paymentCancel() {
        paymentFinish();
        if (mActivity != null) checkUnFinishPay(mActivity);
        if (mPayResultListener != null) mPayResultListener.onCancel();
    }

    public void paymentFail(int code, String msg) {
        paymentFinish();
        if (mActivity != null) checkUnFinishPay(mActivity);
        if (mPayResultListener != null) mPayResultListener.onError(code, msg);
    }

    private SubmitRoleResultListener mSubmitRoleResultListener;
    public void submitGameRoleInfo(Activity activity, GameRoleParams gameRoleParams, SubmitRoleResultListener submitRoleResultListener) {
        if (!isInitialized()) {
            Log.e(TAG, "未初始化");
            return;
        }
        if (!isLogin) {
            Log.e(TAG, "未登录");
            return;
        }
        if (gameRoleParams.getDataType() <= 0 || gameRoleParams.getDataType() > 11) {
            if (submitRoleResultListener != null) submitRoleResultListener.onError(1001, "dataType error");
            return;
        }
        if (gameRoleParams.getRoleId().length() == 0) {
            if (submitRoleResultListener != null) submitRoleResultListener.onError(1001, "roleId error");
            return;
        }
        if (gameRoleParams.getRoleName().length() == 0) {
            if (submitRoleResultListener != null) submitRoleResultListener.onError(1001, "roleName error");
            return;
        }
        if (gameRoleParams.getServerId().length() == 0) {
            if (submitRoleResultListener != null) submitRoleResultListener.onError(1001, "serverId error");
            return;
        }
        if (gameRoleParams.getServerName().length() == 0) {
            if (submitRoleResultListener != null) submitRoleResultListener.onError(1001, "serverName error");
            return;
        }
        if (gameRoleParams.getRoleLevel().length() == 0) {
            if (submitRoleResultListener != null) submitRoleResultListener.onError(1001, "roleLevel error");
            return;
        }
        QSDKHttp.getInstance().submitRole(activity, QSDKHelper.getInstance().getUserInfoModel(activity).getToken(), gameRoleParams, new QResultCallback<QCommonResultBean<String>>(){

            @Override
            public void onSuccess(QCommonResultBean<String> response) {
                if (submitRoleResultListener != null) submitRoleResultListener.onSuccess();
            }

            @Override
            public void onError(int code, String msg) {
                if (submitRoleResultListener != null) submitRoleResultListener.onError(code, msg);
            }
        });

        switch (gameRoleParams.getDataType()) {
            case GameRoleParams.DataType_RoleCreate:
                LogManager.getInstance().roleCreate(activity, gameRoleParams);
                break;
            case GameRoleParams.DataType_RoleLogin:
                LogManager.getInstance().roleLogin(activity, gameRoleParams);
                break;
            case GameRoleParams.DataType_PurchaseFirst:
                LogManager.getInstance().firstPurchase(activity, gameRoleParams);
                break;
            case GameRoleParams.DataType_PurchaseMax:
                LogManager.getInstance().maxPurchase(activity, gameRoleParams);
                break;
            case GameRoleParams.DataType_JoinGangs:
                LogManager.getInstance().joinGangs(activity, gameRoleParams);
                break;
            case GameRoleParams.DataType_FinishGuide:
                LogManager.getInstance().finishGuide(activity, gameRoleParams);
                break;
            case GameRoleParams.DataType_ClickStore:
                LogManager.getInstance().clickStore(activity, gameRoleParams);
                break;
            case GameRoleParams.DataType_AddFriends:
                LogManager.getInstance().addFriends(activity, gameRoleParams);
                break;
            case GameRoleParams.DataType_AcceptFriends:
                LogManager.getInstance().acceptFriends(activity, gameRoleParams);
                break;
            case GameRoleParams.DataType_RoleLevel:
                LogManager.getInstance().level(activity, gameRoleParams);
                break;
            case GameRoleParams.DataType_GameTime:
                LogManager.getInstance().gameTime(activity, gameRoleParams);
                break;
        }
    }

    private ExitResultListener mExitResultListener;
    public void exitGame(Activity activity, ExitResultListener exitResultListener) {
        if (!isInitialized()) {
            Log.e(TAG, "未初始化");
            return;
        }
        if (isExiting()) {
            Log.e(TAG, "退出游戏已显示");
            return;
        }

        mExitResultListener = exitResultListener;
        if (mExitAtomic.getAndSet(true)) {
            Log.e(TAG, "正在展示退出游戏");
            return;
        }

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(activity, ExitActivity.class);
                activity.startActivity(intent);
            }
        });
    }

    public void onResultExitSuccess(Activity activity) {
        onResultExitExec(activity, true, false, 0, "", false);
    }

    public void onResultExitError(Activity activity, int code, String msg) {
        onResultExitExec(activity, false, true, code, msg, false);
    }

    public void onResultExitClose(Activity activity) {
        onResultExitExec(activity, false,  false, 0, "", true);
    }

    private void onResultExitExec(Activity activity, boolean success, boolean error, int code, String msg, boolean close) {
        mExitAtomic.set(false);
        if (mExitResultListener != null) {
            if (success) {
                mExitResultListener.onSuccess();
            }else if (error) {
                mExitResultListener.onError(code, msg);
            }else if (close) {
                mExitResultListener.onClose();
            }
        }
        if (!activity.isFinishing()) activity.finish();
    }

    public void showHistoryAccount(Activity activity, HistoryResultListener historyResultListener) {
        login(activity, true, false, false, new LoginResultListener() {
            @Override
            public void onSuccess(String token) {
                if (historyResultListener != null) historyResultListener.onSuccess(token);
            }

            @Override
            public void onCancel() {
                if (historyResultListener != null) historyResultListener.onClose();
            }

            @Override
            public void onError(int code, String msg) {
                if (historyResultListener != null) historyResultListener.onError(code, msg);
            }
        });
    }

    private ReviewResultListener mReviewResultListener;
    public void showReview(Activity activity, ReviewResultListener reviewResultListener) {
        new AlertDialog.Builder(activity)
                .setTitle(Language.Review_Title.toString())
                .setMessage(Language.Review_Desc.toString())
                .setCancelable(false)
                .setNegativeButton(Language.Review_Cancel.toString(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (reviewResultListener != null) {
                            reviewResultListener.onCancel();
                        }
                        dialog.dismiss();
                    }
                })
                .setPositiveButton(Language.Review_Enter.toString(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        final ReviewManager manager = ReviewManagerFactory.create(activity);
                        Task<ReviewInfo> request = manager.requestReviewFlow();
                        request.addOnCompleteListener(new OnCompleteListener<ReviewInfo>() {
                            @Override
                            public void onComplete(@NonNull Task<ReviewInfo> var1) {
                                if (var1.isSuccessful()) {
                                    Task<Void> flow = manager.launchReviewFlow(activity, var1.getResult());
                                    flow.addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            if (reviewResultListener != null) {
                                                reviewResultListener.onSuccess();
                                            }
                                        }
                                    });
                                }else{
                                    if (reviewResultListener != null) {
                                        reviewResultListener.onSuccess();
                                    }
                                }
                            }
                        });
                    }
                })
                .show();
    }

    private CustomerResultListener mCustomerResultListener;
    public void showService(Activity activity, CustomerResultListener customerResultListener) {
        if (QSDKHelper.getInstance().getConfigureModel().getInitModel().hasCs()) {
            FloatActivity.show(activity, Language.Float_Customer.toString(), QSDKHelper.getInstance().getConfigureModel().getInitModel().getCs_s());
        }
        if (customerResultListener != null) customerResultListener.onSuccess();
    }

    private FacebookLikeResultListener mFacebookLikeResultListener;
    public void showLike(Activity activity, FacebookLikeResultListener facebookLikeResultListener) {
        if (QSDKHelper.getInstance().getConfigureModel().getInitModel().hasFblike()) {
            FloatActivity.show(activity, Language.Float_Customer.toString(), QSDKHelper.getInstance().getConfigureModel().getInitModel().getFacebook_like_url());
        }
        if (facebookLikeResultListener != null) facebookLikeResultListener.onSuccess();
    }

    private GuestBindResultListener mGuestBindResultListener;
    public void showBind(Activity activity, GuestBindResultListener guestBindResultListener) {
        if (!isLogin) {
            if (guestBindResultListener != null) {
                guestBindResultListener.onError(1001, "not login");
                return;
            }
            return;
        }

        if (!isGuest(activity)) {
            if (guestBindResultListener != null) {
                guestBindResultListener.onError(1001, "not guest");
                return;
            }
            return;
        }

        login(activity, false, true, false, new LoginResultListener() {
            @Override
            public void onSuccess(String token) {
                if (guestBindResultListener != null) guestBindResultListener.onSuccess(token);
            }

            @Override
            public void onCancel() {
                if (guestBindResultListener != null) guestBindResultListener.onClose();
            }

            @Override
            public void onError(int code, String msg) {
                if (guestBindResultListener != null) guestBindResultListener.onError(code, msg);
            }
        });
    }

    public boolean isGuest(Activity activity) {
        if (isInitialized() && isLogin) {
            return QSDKHelper.getInstance().getUserInfoModel(activity).isGuest();
        }
        return true;
    }

    public boolean isActive(Activity activity) {
        if (isInitialized() && isLogin) {
            return QSDKHelper.getInstance().getUserInfoModel(activity).isActive();
        }
        return false;
    }

    private Activity mFloatActivity;
    private boolean mCanShowAssistor;
    public void showAssistor(Activity activity) {
        mFloatActivity = activity;
        if (!QSDKHelper.getInstance().getConfigureModel().getInitModel().hasIco()) return;
        if (!isInitialized()) return;
        FloatButtonUtil.show(activity, new QSDKListener(){

            @Override
            public void onFloatClose() {
                mCanShowAssistor = true;
                TipActivity.tip(activity, Language.Float_Again_Show.toString());
            }

            @Override
            public void onFloatCustomer() {
                showService(activity, null);
            }

            @Override
            public void onFloatPay() {
                if (QSDKHelper.getInstance().getConfigureModel().getInitModel().hasRec()) {
                    FloatActivity.show(activity, Language.Float_Pay.toString(), QSDKHelper.getInstance().getConfigureModel().getInitModel().getRec_s());
                }
            }
        });

        if (mSensorManager == null) {
            mSensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
            Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            mSensorManager.registerListener(mSensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    private SensorManager mSensorManager;
    private boolean mShakeEnable = true;
    private SensorEventListener mSensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            if(mShakeEnable && mCanShowAssistor) {
                float xValue = Math.abs(event.values[0]);
                float yValue = Math.abs(event.values[1]);
                float zValue = Math.abs(event.values[2]);
                if (xValue > 25 || yValue > 25 || zValue > 25) {
                    mShakeEnable = false;
                    //震动1.5s
//                    Vibrator vib = (Vibrator) MainActivity.this.getSystemService(Service.VIBRATOR_SERVICE);
//                    vib.vibrate(1500);
                    showAssistor(mFloatActivity);
                    //2秒后可以继续摇一摇
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mShakeEnable = true;
                        }
                    }, 2000);
                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    public void hideAssistor(Activity activity) {
        if (!QSDKHelper.getInstance().getConfigureModel().getInitModel().hasIco()) return;
        if (!isInitialized()) return;
        mCanShowAssistor = false;
        FloatButtonUtil.destroyFloat();
    }

    private void initLanguage(Activity activity) {
        Object save = QSDKHelper.getInstance().getItem(activity, "initLanguage", "");
        String saveLanguage = "";
        if (save != null) {
            saveLanguage = (String)save;
        }

        if (saveLanguage != null && saveLanguage.length() == 0) {
            QSDKHelper.getInstance().setItem(activity, "initLanguage", "1");
            QSDKHelper.getInstance().setItem(activity, Language_Key, QSDKHelper.getInstance().getConfigureModel().getLang());
        }
        Object set = QSDKHelper.getInstance().getItem(activity, Language_Key, "");
        if (set != null) {
            String language = (String)set;
            QSDKHelper.getInstance().getConfigureModel().setCurrencyLang(getLanguage(language));
        }

    }

    public QSDKLanguage getLanguage(String lang) {
        List<QSDKLanguage> qsdkLanguages = QSDKSupportLanguage.getSupportLanguages();
        for (QSDKLanguage l : qsdkLanguages) {
            if (l.toString().equals(lang)) return l;
        }
        return qsdkLanguages.size() > 0 ? qsdkLanguages.get(0) : null;
    }


    private static final String Language_Key = "Language_Key";
    public void switchLanguage(Activity activity, QSDKLanguage languageType, SwitchLanguageListener languageListener) {
        List<QSDKLanguage> supportLangs = QSDKSupportLanguage.getSupportLanguages();
        if (!supportLangs.contains(languageType)) {
            if (languageListener != null) {
                languageListener.onError(1001, Language.System_Not_Support_Lang.toString());
            }
            return;
        }

        if (QSDKHelper.getInstance().getConfigureModel().getCurrencyLang().toString().equals(languageType.toString())) {
            if (languageListener != null) {
                languageListener.onSuccess();
            }
            Publisher.instance().publish(QSDKEvent.CHANGE_LANGUAGE);
            return;
        }

        QSDKHelper.getInstance().getConfigureModel().setCurrencyLang(languageType);
        QSDKHelper.getInstance().setItem(activity, Language_Key, QSDKHelper.getInstance().getConfigureModel().getCurrencyLang().toString());
        if (languageListener != null) {
            languageListener.onSuccess();
        }
        Publisher.instance().publish(QSDKEvent.CHANGE_LANGUAGE);
    }

    public void toggleLanguage(Activity activity) {
        SDKInfoModel model = QSDKHelper.getInstance().getConfigureModel();
        boolean sel = false;
        List<QSDKLanguage> supportLangs = QSDKSupportLanguage.getSupportLanguages();
        for (QSDKLanguage l : supportLangs) {
            if (l.toString().equals(model.getCurrencyLang().toString())) {
                sel = true;
                continue;
            }
            if (sel) {
                switchLanguage(activity, l, null);
                return;
            }
        }
        for (QSDKLanguage l : supportLangs) {
            if (l.toString().equals(model.getCurrencyLang().toString())) {
                sel = true;
                continue;
            }
            if (sel) {
                switchLanguage(activity, l, null);
                return;
            }
        }
    }

    public void onCreate(Activity activity, Bundle savedInstanceState) {}

    public void onStart(Activity activity) {}

    public void onResume(Activity activity) {}

    public void onPause(Activity activity) {}

    public void onStop(Activity activity) {}

    public void onRestart(Activity activity) {}

    public void onNewIntent(Activity activity, Intent intent) {}

    public boolean onKeyDown(Activity activity, int keyCode, KeyEvent event) {return true;}

    public void onBackPressed(Activity activity) {}

    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {}

    public void onDestroy(Activity activity) {}

    public void onConfigurationChanged(Activity activity, Configuration newConfig) {}

    public void onRequestPermissionsResult(Activity activity, int requestCode,
                                                  String[] permissions,
                                                  int[] grantResults) {
    }
}
